/*
 * PixInImage.java
 *
 * Created on October 7, 2007, 7:49 PM
 */

package pd1;

import java.awt.BorderLayout;
import java.awt.Point;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.StringTokenizer;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import morphing.Warping;
import morphing.Warping_;

/**
 *
 * @author  Pizzol
 */
public class PixInImage_2 extends javax.swing.JFrame {
    
    private int who = 0;
    

    private ArrayList<Line2D.Double> referencia;
    private ArrayList alvo;
    
    private ArrayList<Line2D.Double> ref;
    private ArrayList<Line2D.Double> goal;
    private Wait espera;
    private BufferedImage image = null;
    public JPanel panel = null;
    public JFrame f = null;
    
    private boolean isWarp,  isMorph;
    
    public PixInImage_2() {
        initComponents();
        espera = new Wait();
    }
    
    public ArrayList<Line2D.Double> getRef() {
        ArrayList<Line2D.Double> result = new ArrayList<Line2D.Double>();
        for(int i = 0; i < list1.getItemCount(); i++) {
            String item = list1.getItem(i);
            if(countParentesis(item)) {
                result.add(getVector(item));
            }
        }
        return result;
    }
    
    public ArrayList<Line2D.Double> getGoal() {
        ArrayList<Line2D.Double> result = new ArrayList<Line2D.Double>();
        for(int i = 0; i < list2.getItemCount(); i++) {
            String item = list2.getItem(i);
            if(countParentesis(item)) {
                System.out.println("entrou aki");
                result.add(getVector(item));
            }
        }
        return result;
    }
    
    private boolean countParentesis(String s) {
        int count = 0;
        for(int i = 0; i < s.length(); i++) {
            if(s.charAt(i)=='(') {
                count++;
                if (count == 2) {
                    return true;
                }
            }
        }
        return false;
    }
    
    private Line2D.Double getVector(String item) {
        System.out.println(item.substring(item.indexOf("(")+1, item.indexOf(",")));
        int i = Integer.parseInt(item.substring(item.indexOf("(")+1, item.indexOf(",")));
        System.out.println("");
        int j = Integer.parseInt(item.substring(item.indexOf(",")+2, item.indexOf(")")));
        int k = Integer.parseInt(item.substring(item.lastIndexOf("(")+1, item.lastIndexOf(",")));
        int l = Integer.parseInt(item.substring(item.lastIndexOf(",")+2, item.lastIndexOf(")")));
        return new Line2D.Double(i,j,k,l);
    }
    
    /** Creates new form PixInImage */
    public PixInImage_2(BufferedImage im, boolean isWarp, boolean isMorph) {
        image = im;
        this.isMorph = isMorph;
        this.isWarp = isWarp;
        referencia = new ArrayList<Line2D.Double>();
        alvo = new ArrayList<Point>();
        initComponents();
    }
    
    
    public BufferedImage getImage() {
        return image;
    }

    public ArrayList<Line2D.Double> getReferencia(){
        return referencia;
    }
    
    public ArrayList<Line2D.Double> getAlvo(){
        return alvo;
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        list1 = new java.awt.List();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        list2 = new java.awt.List();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Pixel (X, Y)");
        jLabel1.setText("Pixel Escolhido (X, Y):");

        jLabel2.setText("(0, 0)");

        jButton1.setText("Adicionar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Warp");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel3.setText("Vetor refer\u00eancia");

        jLabel5.setText("Vetor alvo");

        jLabel6.setText("Pixel Atual: (X, Y)");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(list1, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(list2, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addGap(16, 16, 16)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addGap(33, 33, 33)
                                        .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(jLabel6)
                                            .addComponent(jLabel1))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                            .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                            .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, 77, Short.MAX_VALUE))))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, 130, Short.MAX_VALUE)
                                    .addComponent(jButton1)))))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(147, 147, 147)
                        .addComponent(jButton2)))
                .addGap(36, 36, 36))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(6, 6, 6)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(6, 6, 6)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(list1, javax.swing.GroupLayout.DEFAULT_SIZE, 148, Short.MAX_VALUE)
                    .addComponent(list2, javax.swing.GroupLayout.DEFAULT_SIZE, 148, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton2)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    
        this.setVisible(false);
        f.dispose();
        
        JInternalFrame pic1Frame = new JInternalFrame();
        
        pic1Frame.setClosable(true);
        pic1Frame.setResizable(true);
        pic1Frame.setMaximizable(true);
        pic1Frame.setTitle("Warping: Imagem Fonte");
        panel.add(pic1Frame);
        
        JLabel pic1Label = new JLabel(new ImageIcon(image.getScaledInstance(image.getWidth(),image.getHeight(),3)));
        
        pic1Frame.add(pic1Label, BorderLayout.CENTER);
        
        pic1Label.setVisible(true);
        
        pic1Frame.setVisible(true);
        
        espera.setVisible(true);
        
        ArrayList<Line2D.Double> reference = this.getRef();
        ArrayList<Line2D.Double> goal = this.getGoal();
        
        if(reference.size()>goal.size())
            reference.remove(reference.size()-1);
        
        Warping warp = new Warping(true);
        /*reference = new ArrayList<Line2D.Double>();
        reference.add(new Line2D.Double(155,292,155,46));
        reference.add(new Line2D.Double(155,46,334,46));
        reference.add(new Line2D.Double(334,46,334,292));
        reference.add(new Line2D.Double(334,292,155,292));
        
        goal = new ArrayList<Line2D.Double>();
        goal.add(new Line2D.Double(202,245,202,89));
        goal.add(new Line2D.Double(202,89,292,89));
        goal.add(new Line2D.Double(292,89,292,245));
        goal.add(new Line2D.Double(292,245,202,245));*/
        
        BufferedImage finalImg = null;

        finalImg = warp.warping(reference, goal, image);
        
        JInternalFrame picFrame = new JInternalFrame();
        
        picFrame.setClosable(true);
        picFrame.setResizable(true);
        picFrame.setMaximizable(true);
        picFrame.setTitle("Warping: Imagem Resultante");
        panel.add(picFrame);
        
        JLabel picLabel = new JLabel(new ImageIcon(finalImg.getScaledInstance(finalImg.getWidth(),finalImg.getHeight(),3)));
        
        picFrame.add(picLabel, BorderLayout.CENTER);
        
        picLabel.setVisible(true);
        
        picFrame.setVisible(true);
        
        
        espera.setVisible(false);
       
      
      
    }//GEN-LAST:event_jButton2ActionPerformed

     public void warp() {
        
                    Warping_ warp = new Warping_(true);
                    
                    System.out.println("ref: "+referencia.size());
                    System.out.println("alvo: "+alvo.size());
                    
                    BufferedImage resultado = warp.warping(this.getReferencia(),this.getAlvo(),this.getImage());
        try {
            
            ImageIO.write(resultado, "PNG", new File("c:/teresa.png"));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
                    
                    JInternalFrame picFrame = new JInternalFrame();
                  
                    picFrame.setClosable(true);
                    picFrame.setResizable(true);
                    picFrame.setMaximizable(true);
                    picFrame.setTitle("Warping: Resultado");
                    
                    JLabel picLabel = new JLabel(new ImageIcon(resultado.getScaledInstance(resultado.getWidth(),resultado.getHeight(),3)));
                    
                    picFrame.add(picLabel, BorderLayout.CENTER);
                    
                    jPanel1.add(picFrame);
                    jPanel1.setVisible(true);
                    
                    picFrame.setVisible(true);
                    picLabel.setVisible(true);
               
    }
    
    
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        if(!(jLabel2.getText().equals(("(X, Y)")))) {
            int it = list1.getItemCount();
            int it2 = list2.getItemCount();
                  System.out.println(" who "+who);
            if(who == 0 || who == 1 ) {
                if(who == 1) {
                    String temp = list1.getItem(it-1);
                    list1.remove(it-1);
                    list1.add(temp+" - "+jLabel2.getText());
                     who = -1;
                }else {
                    list1.add(jLabel2.getText());
                    who++;
                }
             
            }
            else {
          
                if(who == -2) {
                    String temp = list2.getItem(it2-1);
                    list2.remove(it2-1);
                    list2.add(temp+" - "+jLabel2.getText());
                    who = 0;
                }else {
                    list2.add(jLabel2.getText());
                    who--;
                }
                 
            }
            
            /*
            
            if(it>0) {
                if(list1.getItem(it-1).endsWith("-")) {
                    String item = list1.getItem(it-1).toString();
                    list1.remove(it-1);
                    
                    item+=" "+jLabel2.getText()+" |";
                    
                    list1.add(item);
                }
                else {
                    list1.add(jLabel2.getText()+" -");
                }
            }
            else {
                list1.add(jLabel2.getText()+" -");
            }*/
        } 
    }//GEN-LAST:event_jButton1ActionPerformed
    
    public void setImage(BufferedImage bi) {
        image = bi;
    }
    
    public void setPoint(int x, int y) {
        jLabel2.setText("("+x+", "+y+")");
    }
    
    public void setPoint2(int x, int y) {
        jLabel4.setText("("+x+", "+y+")");
    }
    
    /**
     * @param args the command line arguments
     
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new PixInImage().setVisible(true);
            }
        });
    }
    */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    public javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    public javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private java.awt.List list1;
    private java.awt.List list2;
    // End of variables declaration//GEN-END:variables
    
}
